<template>
  <el-drawer
    @close="close"
    :visible.sync="dialogVisible"
    :title="title"
    :size="500"
  >
    <el-row :gutter="10" class="box-card">
      <el-form
        ref="elForm"
        :model="formData"
        :rules="rules"
        size="small"
        label-width="100px"
      >
        <!-- <el-col :span="24">
          <el-form-item label="活动类型" prop="hdType">
            <el-input v-model="$partyType[formData.hdType]" placeholder="请输入活动类型" clearable disabled :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item label="活动标题" prop="title">
            <el-input
              v-model="formData.title"
              placeholder="请输入活动标题"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="活动封面" title="picUrl">
            <el-upload
              action=""
              :show-file-list="false"
              :http-request="uploadFile"
              :beforeUpload="beforeAvatarUpload"
              class="avatar-uploader"
              accept=".jpg,.jpeg,.png,.gif"
            >
              <img
                v-if="formData.picUrl"
                :src="formData.picUrl"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="活动地址" prop="address">
            <el-input
              v-model="formData.address"
              placeholder="请输入活动地址"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="24">
          <el-form-item label="签到范围" prop="fanwei">
            <el-input
              v-model="formData.fanwei"
              type="number"
              placeholder="请输入活动地址签半径"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item label="所属社区" prop="hdsq">
            <el-select
              v-model="formData.hdsq"
              placeholder="请选择社区"
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="(item, index) in deptOptions"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="formData.startTime"
              type="datetime"
              placeholder="选择日期"
              value-format="yyyy-MM-dd HH:mm"
              format="yyyy-MM-dd HH:mm"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="formData.endTime"
              type="datetime"
              placeholder="选择日期"
              value-format="yyyy-MM-dd HH:mm"
              format="yyyy-MM-dd HH:mm"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="活动人数" prop="hdrs">
            <el-input
              v-model="formData.hdrs"
              type="number"
              placeholder="请输入活动人数"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="联系人" prop="lxr">
            <el-input
              v-model="formData.lxr"
              type="text"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="联系电话" prop="phone">
            <el-input
              v-model="formData.phone"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="活动内容" prop="detail">
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入活动内容"
              v-model="formData.detail"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <div class="footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="handelConfirm">确定</el-button>
    </div>
  </el-drawer>
</template>
<script>
import { saveActivity } from '@/api/activity'
import { queryList } from '@/api/dept'
import axios from 'axios'
import { uploadImg } from '@/api/files'
import { getImgUrl } from '@/filters/filters'
export default {
  props: [],
  data () {
    const startTime = (rules, value, callback) => {
      if (!value) {
        callback(new Error('请选择开始时间'))
      } else {
        if (this.formData.endTime) {
          this.$refs.elForm.validateField('endTime')
        }
        callback()
      }
    }
    const endTime = (rules, value, callback) => {
      if (!value) {
        callback(new Error('请选择结束时间'))
      } else {
        if (!this.formData.startTime) {
          callback(new Error('请选择开始时间！'))
        } else if (Date.parse(this.formData.startTime) >= Date.parse(value)) {
          callback(new Error('结束时间必须大于开始时间！'))
        } else {
          callback()
        }
      }
    }
    return {
      dialogVisible: false,
      formData: {
        hdType: '', // 活动类型
        address: '', // 活动地址
        area: '', // 经纬度
        bmrs: '', // 报名人数
        title: '', // 活动标题
        hdrs: '', // 活动人数
        detail: '', // 活动内容
        startTime: '',
        endTime: '',
        hdsq: '', // 所属社区
        lxr: '', // 联系人
        phone: '', // 联系电话
        picUrl: '', // 活动图片
        fanwei: '100' // 签到范围
      },
      rules: {
        title: [
          {
            required: true,
            message: '请输入活动标题',
            trigger: 'blur'
          }
        ],
        address: [
          {
            required: true,
            message: '请输入活动地址',
            trigger: 'blur'
          }
        ],
        fanwei: [
          {
            required: true,
            message: '请输入签到范围值',
            trigger: 'blur'
          }
        ],
        hdsq: [
          {
            required: true,
            message: '请选择所属社区',
            trigger: 'blur'
          }
        ],
        startTime: [
          {
            required: true,
            validator: startTime,
            trigger: 'blur'
          }
        ],
        endTime: [
          {
            required: true,
            validator: endTime,
            trigger: 'blur'
          }
        ],
        hdrs: [
          {
            required: true,
            message: '请输入活动人数',
            trigger: 'blur'
          }
        ],
        lxr: [
          {
            required: true,
            message: '请输入联系人',
            trigger: 'blur'
          },
          { pattern: /^[\u4e00-\u9fa5]+$/, message: '联系人请用汉字填写', trigger: 'blur' }
        ],
        phone: [
          {
            required: true,
            message: '请输入联系电话',
            trigger: 'blur'
          },
          { pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/, message: '电话格式不正确', trigger: 'blur' }
        ]
      },
      deptOptions: [],
      title: '新增活动',
      id: null,
      isEdit: false
    }
  },
  mounted () {
    this.getDeptAndRole()
  },
  methods: {
    async uploadFile (files) {
      // FormData 对象
      const form = new FormData()
      // 文件对象
      form.append('file', files.file)
      const { url } = await uploadImg(form, { fileSize: files.file.size })
      this.formData.picUrl = getImgUrl(url)
    },
    beforeAvatarUpload (file) {
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$notify({
          message: '上传文件大小不能超过 5MB!',
          type: 'warning'
        })
      }
      return isLt5M
    },
    /**
     *
     * @param {*} isEdit 是否编辑
     * @param {*} data 编辑时需要的数据
     */
    async isShow (data, isEdit = false) {
      this.dialogVisible = true
      this.title = isEdit ? '编辑活动' : '新增活动'
      this.isEdit = isEdit
      this.formData.picUrl = null
      await this.$nextTick()
      if (isEdit) {
        const formData = this.formData
        for (const key in formData) {
          formData[key] = data[key]
        }
        this.formData.hdsq = data?.hdsqId || data.hdsq
        this.id = data.id
      } else {
        this.formData.hdType = data
      }
    },
    // 获取部门和角色
    getDeptAndRole () {
      queryList().then((res) => {
        this.deptOptions = res
      })
    },
    close () {
      this.$refs.elForm.resetFields()
      this.dialogVisible = false
    },
    async handelConfirm () {
      await this.convertCoordinates()
      this.$refs.elForm.validate(async (valid) => {
        if (!valid) return
        const params = JSON.parse(JSON.stringify(this.formData))
        params.startTime = params.startTime + ':00'
        params.endTime = params.endTime + ':00'
        this.isEdit
          ? await saveActivity({ ...params, id: this.id })
          : await saveActivity(params)
        this.$notify.success({
          title: `完成${this.title}`
        })
        this.$emit('update:visible')
        this.close()
      })
    },
    async convertCoordinates () {
      const key = 'b22f4741ea59178bd048c675b36798ce' // 替换为自己的高德地图API密钥
      // 发送HTTP GET请求获取转换结果
      const url = `https://restapi.amap.com/v3/geocode/geo?address=${this.formData.address}&key=${key}`
      const response = await axios.get(url)
      const { geocodes } = response.data
      const [item] = geocodes
      const { location } = item // 经纬度
      this.formData.area = location
    }
  }
}
</script>
<style lang="scss" scoped>
.box-card {
  margin-bottom: 10px;
  padding-right: 20px;
  width: 100%;
  padding-left: 10px;
}
.footer {
  display: flex;
  justify-content: space-around;
  margin-bottom: 40px;
  padding-left: 110px;
  padding-right: 20px;
  .el-button {
    width: 100%;
  }
}

.avatar-uploader ::v-deep .el-upload {
  width: 145px;
  height: 145px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>
